package com.ceadeal.admin.util;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;

import java.util.Base64;

/**
 * 功能描述: 数据加密
 * <p>
 * 作者: Yzw
 * 日期: 2017-03-02 14:01:33
 */
public class EncryptUtil {

    private static PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(10);

    /**
     * 功能描述: 密码非可逆加密
     *
     * @param
     * @return
     * @throws
     * @author Yzw
     * @date 2017-03-02 14:01:57
     */
    public static String encode(CharSequence rawPassword) {
        return passwordEncoder.encode(rawPassword);
    }

    /**
     * 功能描述: 加密密码和非加密密码匹配
     *
     * @param
     * @return
     * @throws
     * @author Yzw
     * @date 2017-03-02 14:02:28
     */
    public static Boolean matches(CharSequence rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 功能描述: 获取加密实体
     *
     * @param
     * @return
     * @throws
     * @author Yzw
     * @date 2017-03-02 14:02:38
     */
    public static PasswordEncoder getPasswordEncoder() {
        return passwordEncoder;
    }

    /**
     * 功能描述: API账户密码加密算法（SHA256+Hex编码）
     *
     * @param
     * @return
     * @throws
     * @author Yzw
     * @date 2017-03-02 14:03:38
     */
    public static String encodeAPI(String rawPassword) {
        if (StringUtils.isEmpty(rawPassword)) {
            return null;
        }
        return org.apache.commons.codec.digest.DigestUtils.sha256Hex(rawPassword);
    }

    /**
     * 功能描述: API账户密码匹配（SHA256+Hex编码）
     *
     * @param
     * @return
     * @throws
     * @author Yzw
     * @date 2017-03-02 14:03:52
     */
    public static Boolean matchAPI(String rawPassword, String encodedPassword) {
        if (StringUtils.isEmpty(rawPassword) || StringUtils.isEmpty(encodedPassword)) {
            return false;
        }

        return encodedPassword.equalsIgnoreCase(rawPassword) || encodedPassword.equalsIgnoreCase(encodeAPI(rawPassword));
    }

    public static void main(String[] args) {
        String str = EncryptUtil.encode("123456");
        System.out.println(str);

        byte[] bytes = Base64.getEncoder().encode("client:fuck_secret".getBytes());
        System.out.println(new String(bytes));
    }

}
